using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Text.Json;
using Test.Mvc.Models;
using Test.Mvc.Services;

namespace Test.Mvc.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly TestWeatherService _weatherService;
        public HomeController(ILogger<HomeController> logger, TestWeatherService weatherService)
        {
            _logger = logger;
            _weatherService = weatherService;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }






        // 天气查询页（GET）
        [HttpGet]
        public IActionResult weather()
        {
            var model = new TestWeatherViewModel();
            return View("~/Views/Weather/weather.cshtml", model);
        }

        public IActionResult TestProductionPlan()
        {

            var model = new TestPlanModel
            {
                TestProductItems = new System.Collections.Generic.List<TestProductItem>()
            };
            return View(model);
        }


        public IActionResult TestProductionPlanDetail()
        {

            return View();
        }


        public IActionResult TestProductionPlanList()
        {

            var queryModel = new TestProductionPlanQueryModel();
            var result = new TestProductionPlanPagedResult
            {
                Items = new System.Collections.Generic.List<TestProductionPlanItem>(),
                TotalCount = 0,
                PageIndex = 1,
                PageSize = 15
            };
            ViewBag.QueryModel = queryModel;
            return View(result);
        }





        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> weather(TestWeatherViewModel model)
        {
            try
            {
                var forecasts = await _weatherService.GetForecastAsync(
                    model.Latitude,
                    model.Longitude
                );
                model.Forecasts = forecasts;


                model.LocationName = await GetLocationNameAsync(model.Latitude, model.Longitude);
                if (string.IsNullOrWhiteSpace(model.LocationName) ||
                    model.LocationName == "未知地点")
                {
                    model.LocationName = null; // 规范未知地点，不在页面展示
                }

                ModelState.Clear();
                return View("~/Views/Weather/weather.cshtml", model);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", $"获取天气失败：{ex.Message}");
                return View("~/Views/Weather/weather.cshtml", model);
            }
        }


        private async Task<string> GetLocationNameAsync(double latitude, double longitude)
        {

            var locationName = await TryOpenMeteoReverse(latitude, longitude);
            if (!string.IsNullOrWhiteSpace(locationName) && locationName != "未知地点")
                return locationName;


            locationName = await TryNominatimAPI(latitude, longitude);
            if (locationName != "未知地点")
                return locationName;


            return await TryBackupGeocoding(latitude, longitude);
        }


        private async Task<string> TryOpenMeteoReverse(double latitude, double longitude)
        {
            try
            {
                using var httpClient = new HttpClient();
                httpClient.Timeout = TimeSpan.FromSeconds(10);
                var url = $"https://geocoding-api.open-meteo.com/v1/reverse?latitude={latitude:F6}&longitude={longitude:F6}&language=zh-CN";
                var response = await httpClient.GetStringAsync(url);
                using var jsonDoc = JsonDocument.Parse(response);
                var root = jsonDoc.RootElement;
                if (root.TryGetProperty("results", out var results) && results.ValueKind == JsonValueKind.Array && results.GetArrayLength() > 0)
                {
                    var first = results[0];
                    if (first.TryGetProperty("name", out var nameEl))
                    {
                        var name = nameEl.GetString();
                        if (!string.IsNullOrWhiteSpace(name))
                            return name;
                    }
                    if (first.TryGetProperty("admin1", out var admin1))
                    {
                        var name = admin1.GetString();
                        if (!string.IsNullOrWhiteSpace(name))
                            return name;
                    }
                }
                return "未知地点";
            }
            catch
            {
                return "未知地点";
            }
        }


        private async Task<string> TryNominatimAPI(double latitude, double longitude)
        {
            try
            {
                using var httpClient = new HttpClient();
                httpClient.Timeout = TimeSpan.FromSeconds(10);

                var url = $"https://nominatim.openstreetmap.org/reverse?format=json&lat={latitude:F6}&lon={longitude:F6}&zoom=10&accept-language=zh-CN";
                httpClient.DefaultRequestHeaders.Add("User-Agent", "WeatherApp/1.0");

                var response = await httpClient.GetStringAsync(url);
                var jsonDoc = JsonDocument.Parse(response);
                var root = jsonDoc.RootElement;

                if (root.TryGetProperty("error", out var error))
                    return "未知地点";

                if (root.TryGetProperty("address", out var address))
                {

                    if (address.TryGetProperty("city", out var city) && !string.IsNullOrEmpty(city.GetString()))
                        return city.GetString();
                    if (address.TryGetProperty("town", out var town) && !string.IsNullOrEmpty(town.GetString()))
                        return town.GetString();
                    if (address.TryGetProperty("village", out var village) && !string.IsNullOrEmpty(village.GetString()))
                        return village.GetString();
                    if (address.TryGetProperty("county", out var county) && !string.IsNullOrEmpty(county.GetString()))
                        return county.GetString();
                    if (address.TryGetProperty("state", out var state) && !string.IsNullOrEmpty(state.GetString()))
                        return state.GetString();
                    if (address.TryGetProperty("province", out var province) && !string.IsNullOrEmpty(province.GetString()))
                        return province.GetString();
                }

                if (root.TryGetProperty("display_name", out var displayName))
                {
                    var name = displayName.GetString();
                    if (!string.IsNullOrEmpty(name))
                    {
                        var parts = name.Split(',');
                        return parts.Length > 0 ? parts[0].Trim() : name;
                    }
                }

                return "未知地点";
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"Nominatim API 出错: {ex.Message}");
                return "未知地点";
            }
        }


        private async Task<string> TryBackupGeocoding(double latitude, double longitude)
        {

            var cities = new Dictionary<string, (double minLat, double maxLat, double minLon, double maxLon)>
            {
                {"上海", (30.5, 32.0, 120.5, 122.5)},
                {"北京", (39.0, 41.0, 115.5, 117.5)},
                {"广州", (22.5, 24.0, 112.5, 114.5)},
                {"深圳", (22.0, 23.0, 113.5, 114.5)},
                {"杭州", (29.5, 31.0, 119.5, 121.0)},
                {"南京", (31.5, 33.0, 118.0, 120.0)},
                {"武汉", (29.5, 31.0, 113.5, 115.5)},
                {"成都", (30.0, 31.5, 103.5, 105.5)},
                {"重庆", (29.0, 30.5, 106.0, 108.0)},
                {"西安", (33.5, 35.0, 108.0, 110.0)},
                {"廊坊", (38.5, 40.0, 116.5, 118.5)},
                {"青岛", (35.5, 37.0, 120.0, 122.0)},
                {"大连", (38.5, 40.0, 120.5, 122.5)},
                {"厦门", (24.0, 25.5, 117.5, 119.0)},
                {"苏州", (30.5, 32.0, 120.0, 121.5)},
                {"南通", (31.0, 32.0, 120.0, 121.0)},
                {"舟山", (29.5, 30.5, 121.0, 122.5)},
                {"长沙", (27.5, 29.0, 112.5, 114.0)},
                {"郑州", (34.0, 35.5, 113.0, 115.0)},
                {"济南", (36.0, 37.5, 116.5, 118.5)}
            };

            foreach (var city in cities)
            {
                if (latitude >= city.Value.minLat && latitude <= city.Value.maxLat &&
                    longitude >= city.Value.minLon && longitude <= city.Value.maxLon)
                {
                    return city.Key;
                }
            }

            return "未知地点";
        }



    }
}
